<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<html>
<head>
  <meta charset="utf-8">
  <link rel="stylesheet" href="${httpServletRequest.getContextPath()}/css/layui.css"  media="all">
  <title>乒乓聊天</title> 
  <script src="${httpServletRequest.getContextPath()}/jquery.min.js"></script>
  <script src="${httpServletRequest.getContextPath()}/layer.js"></script>
  <script src="${httpServletRequest.getContextPath()}/layui.js"></script>
  <style type="text/css">
         .sender{
            clear:both;
        }
        .sender div:nth-of-type(1){
            float: left;
        }
        .sender div:nth-of-type(2){
            background-color: aquamarine;
            float: left;
            margin: 0 20px 10px 15px;
            padding: 10px 10px 10px 0px;
            border-radius:7px;
        }

        .receiver div:first-child img,
        .sender div:first-child img{
            width:50px;
            height: 50px;
        }

        .receiver{
            clear:both;
        }
        .receiver div:nth-child(1){
            float: right;
        }
        .receiver div:nth-of-type(2){
            float:right;
            background-color: gold;
            margin: 0 10px 10px 20px;
            padding: 10px 0px 10px 10px;
            border-radius:7px;
        }

        .left_triangle{
            height:0px;  
            width:0px;  
            border-width:8px;  
            border-style:solid;  
            border-color:transparent aquamarine transparent transparent;  
            position: relative;
            left:-16px;
            top:3px;
        }

        .right_triangle{
            height:0px;  
            width:0px;  
            border-width:8px;  
            border-style:solid;  
            border-color:transparent transparent transparent gold;  
            position: relative;
            right:-16px;
            top:3px;
        }
        
        .divcss5-b{ margin-left:10px;height:250px;hoverflow-y:scroll; overflow-x:scroll;} 
        
        .myskin{
             background-color:transparent;//透明（可根据需求自己调整）
             opacity: 0.3;//透明度
        }
    </style>
</head>
<body>
 <img alt="" style="display:none;" id="displayImg" src="" height="500" width="500"/>
<script>
layui.use('element', function(){
  var $ = layui.jquery
  ,element = layui.element; //Tab的切换功能，切换事件监听等，需要依赖element模块
  
  //触发事件
  var active = {
    tabAdd: function(){
      //新增一个Tab项
      element.tabAdd('demo', {
        title: '新选项'+ (Math.random()*1000|0) //用于演示
        ,content: '内容'+ (Math.random()*1000|0)
        ,id: new Date().getTime() //实际使用一般是规定好的id，这里以时间戳模拟下
      })
    }
    ,tabDelete: function(othis){
      //删除指定Tab项
      element.tabDelete('demo', '44'); //删除：“商品管理”
      
      
      othis.addClass('layui-btn-disabled');
    }
    ,tabChange: function(){
      //切换到指定Tab项
      element.tabChange('demo', '22'); //切换到：用户管理
    }
  };
  
  $('.site-demo-active').on('click', function(){
    var othis = $(this), type = othis.data('type');
    active[type] ? active[type].call(this, othis) : '';
  });
  
  //Hash地址的定位
  var layid = location.hash.replace(/^#test=/, '');
  element.tabChange('test', layid);
  
  element.on('tab(test)', function(elem){
    location.hash = 'test='+ $(this).attr('lay-id');
  });
  
});
</script>

<script>
//用户编号
var userCode="${userCode}";
var userName="${userName}";
var layedit;
var indexMap=new Map();

//这里保存没有打开对话框的数据
var alertChatMsg=new Set();
var alertChatCount=0;

;!function(){
//页面一打开就执行，放入ready是为了layer所需配件（css、扩展模块）加载完毕
layer.ready(function(){ 
  layer.open({
    type: 1,
    title: '${userName}',
    maxmin: true,
	closeBtn: 0,
    area: ['300px', '500px'],
	offset: ['60px', '200px'],
	cancel : function(){
				              // 你点击右上角 X 取消后要做什么
					},
    content: '<div class="layui-tab">'+
  '<ul class="layui-tab-title">'+
   '<li class="layui-this">好友</li>'+
    '<li>群组</li>'+
    '<li>最近聊天</li>'+
  '</ul>'+
  '<div class="layui-tab-content">'+
    '<div class="layui-tab-item layui-show">'+
        '<dl id="user_list">'+
          /*
          '<dd><a onclick="chatSingle(\'s003\',\'3\')">张三</a></dd>'+
          '<dd><a onclick="chatSingle(\'s004\',\'3\')">李四</a></dd>'+
          '<dd><a onclick="chatSingle(\'s005\',\'3\')">王五</a></dd>'+
          */
        '</dl>'+
    '</div>'+
    '<div class="layui-tab-item">'+
	    '<dl>'+
          '<dd><a onclick="chatSingle(\'群组(g001)\',\'g001\',\'4\')">群组(g001)</a></dd>'+
          '<dd><a onclick="chatSingle(\'群组(g002)\',\'g002\',\'4\')">群组(g002)</a></dd>'+
          '<dd><a onclick="chatSingle(\'群组(g003)\',\'g003\',\'4\')">群组(g003)</a></dd>'+
        '</dl>'+
	'</div>'+
    '<div class="layui-tab-item">内容3</div>'+
  '</div>'+
'</div>'
  });
});
}();

function chatSingle(toUserName,toUserCode,cmd){
if($("#chat"+toUserCode).length>0){
 return false;
};

 layer.open({
    type: 1,
    title: userName+"---->"+toUserName,
    maxmin: true,
    area: ['600px', '500px'],
	offset: ['60px', '600px'],
	shade: 0,
    content: '<div id="chat'+toUserCode+'" class="divcss5-b"></div>'+
	         '<div style="position:absolute;left:0;bottom:0;">'+
	           '<div style="margin-bottom: 20px; width: 500px;">'+
                    '<textarea class="layui-textarea" id="LAY_demo'+toUserCode+'"></textarea>'+
               '</div>'+
                  '<button class="layui-btn" lay-submit lay-filter="formDemo" onclick="send(\''+toUserCode+'\',\''+cmd+'\');">发送</button>'+
              '</div>'
	});
 
 layui.use('layedit', function(){
	 if(null==layedit){
	  layedit = layui.layedit;
	 }
	 
	 layedit.set({
		                uploadImage: {
		                     url: '${httpServletRequest.getContextPath()}/fileUpload/imageUpload' //接口url
		                    ,type: 'post' //默认post
		                },
						uploadVideo: {
							 url: '${httpServletRequest.getContextPath()}/fileUpload/imageUpload', //接口url
					         accept: 'video',
					         acceptMime: 'video/*',
					         exts: 'mp4|flv|avi|rm|rmvb'
					     },
					     uploadAudio: {
					    	 url: '${httpServletRequest.getContextPath()}/fileUpload/imageUpload', //接口url,
					         accept: 'audio',
					         acceptMime: 'audio/*',
					         exts: 'mp3|m4a|wma|amr|ape|flac|aac'
					     }
		            });
	 
     //var index;
	  //,$ = layui.jquery;
	  //自定义工具栏
	 var index=layedit.build('LAY_demo'+toUserCode, {
	    tool: ['face', 'left', 'center', 'right','image','video', 'audio']
	    ,height: 100
	  });
     indexMap.set(toUserCode,index);
	});	
};

function send(name,cmd){
  console.log(name+" "+cmd);
  console.log(layedit.getContent(indexMap.get(name)));
  console.log(layedit.getText(indexMap.get(name)));
  //var text=$('.layui-textarea').val();
  var text=layedit.getContent(indexMap.get(name));
    //$("#chat"+name).append("<p>"+userCode+":"+HTMLEncode(text)+"</p>");
    $("#chat"+name).append(" <div class=\"receiver\"><div>"+userName+"("+userCode+")</div><div><div class=\"right_triangle\"></div><span>"+text+"</span></div>");
//</div><span>"+userCode+":"+text+"</span>");
	//$('.layui-textarea').val('');
	layedit.setContent(indexMap.get(name),"");
	var bindMsg = {};
	var from ={};
	var accept={};
	
    from.userCode=userCode;
    bindMsg.cmd=cmd;
    bindMsg.from=from;
    
    if("3"==cmd){
    	accept.userCode=name;
    	bindMsg.accept=accept;
	    //bindMsg.accept=name;
    }else if("4"==cmd){
      bindMsg.group=name;
    }
	bindMsg.msg=text;
    ws.send(JSON.stringify(bindMsg));
	//ws.send(text);
};

//HTML转义
function HTMLEncode(html) {
var temp = document.createElement("div");
(temp.textContent != null) ? (temp.textContent = html) : (temp.innerText = html);
var output = temp.innerHTML;
temp = null;
return output;
};

var ws = new WebSocket("ws://${chatPath}:8089/ws");
ws.onopen = function(){  
   console.log("open");
   //初始化绑定信息
   var bindMsg = {};
   var from={};
   
   bindMsg.cmd="1";
   from.userCode=userCode;
   from.userName=userName;
   bindMsg.from=from;
   console.log("登录");
   ws.send(JSON.stringify(bindMsg));
};

ws.onmessage = function(evt){
  //$("#testChat").append(" <p>"+evt.data+"</p>");
  console.log(evt.data);
  if("pong"==evt.data){
	  return;
  }else if("Heartbeat"==evt.data){
   ws.send("Heartbeat");
	return;  
  }
  
  console.log(eval("("+evt.data+")"));
  var message=eval("("+evt.data+")");
  if("3"==message.cmd){
	  if($("#chat"+message.from.userCode).length<=0){
		  alertChatMsg.add(message);
		  alertChatCount=alertChatMsg.size;
	      alertMsg();
		  return false;
	  }
    //console.log("#chat"+message.from);
    //$("#chat"+message.from).append(" <p>"+message.from+":"+message.msg+"</p>");
    $("#chat"+message.from.userCode).append("<div class=\"sender\"><div>"+message.from.userName+"("+message.from.userCode+")</div><div><div class=\"left_triangle\"></div><span>"+message.msg+"</span></div>");
  }else if("4"==message.cmd){
	//$("#chat"+message.group).append(" <p>"+message.from+":"+message.msg+"</p>");
	  if($("#chat"+message.group).length<=0){
		  alertChatMsg.add(message);
		  alertChatCount=alertChatMsg.size;
	      alertMsg();
		  return false;
	  } 
	$("#chat"+message.group).append("<div class=\"sender\"><div>"+message.from.userName+"("+message.from.userCode+")</div><div><div class=\"left_triangle\"></div><span>"+message.msg+"</span></div>");
  }else if("5"==message.cmd){
	  var currentUser=message.chatSet;
	  $("#user_list").html("");
	  for(var i = 0; i < currentUser.length; i++){
	     console.log(currentUser[i].userCode + " " + currentUser[i].userName);
	     $("#user_list").append('<dd><a onclick="chatSingle(\''+currentUser[i].userName+'\',\''+currentUser[i].userCode+'\',\'3\')">'+currentUser[i].userName+'('+currentUser[i].userCode+')</a></dd>');
	  }
  }
};

ws.onclose = function(evt){
  console.log("WebSocketClosed!");
};

ws.onerror = function(evt){
  console.log("WebSocketError!");
};

//---------------------------
//获取所用用户
function getAllUser(){
	 var bindMsg = {};
	 var from={};
	 bindMsg.cmd="5";
	 from.userCode=userCode;
	 bindMsg.from=from;
	 ws.send(JSON.stringify(bindMsg));
}
setInterval(getAllUser ,1000); 
//---------------------------

function test(){ 
	ws.send("ping");
	console.log("ping");
} 
setInterval(test ,11000); 

function alertMsg(){
	 var index=layer.open({
		  type: 0,
		  shade: 0,
		  title: '消息提醒',
		  content: '你有'+alertChatCount+"条消息未接受!",
		  offset: 'rb',
		  yes: function(){
			   for(var message of alertChatMsg){
				   if("3"==message.cmd){
				       chatSingle(message.from.userName,message.from.userCode,message.cmd);
					   $("#chat"+message.from.userCode).append("<div class=\"sender\"><div>"+message.from.userName+"("+message.from.userCode+")</div><div><div class=\"left_triangle\"></div><span>"+message.msg+"</span></div>");
				   }else if("4"==message.cmd){
					   chatSingle("群组("+message.group+")",message.group,message.cmd);
					   $("#chat"+message.group).append("<div class=\"sender\"><div>"+message.from.userName+"("+message.from.userCode+")</div><div><div class=\"left_triangle\"></div><span>"+message.msg+"</span></div>");
				   }
			   }
			   alertChatMsg.clear();
			   parent.layer.close(index); //再执行关闭
	      }
	   });
}

$(document).on('click', '#im_img', function() {
	        var url = $(this).attr('src').replace('_2', '');
	        console.log("图片原图："+url);
	        $("#displayImg").attr("src", url);
	        var height = $("#displayImg").height();
	        var width = $("#displayImg").width();
	        layer.open({
	           type: 1,
	           title: false,
	           closeBtn: 0,//隐藏关闭按钮
	           shade: [0.3, '#000'],//黑色背景（0.3代表颜色深度）
	           shadeClose: true,//点击遮罩关闭大图
	           area: [width + 'px', height + 'px'], //宽高
	           resize:false,//不可拖拽缩放
	           skin: 'myskin',//大图背景色定义类
	           content: "<img  src=" + url + " height=500px; width=500px;" + "/>"
	        });
	    })

</script>
</body>
</html>